import { User } from '../modele/User.js'
import { Op } from 'sequelize';

//定义路由的行为

//查询所有用户
async function queryAll(ctx) {

    let keyword = ctx.request.query.keyword;
    console.log(keyword);

    let users;

    if (keyword) {
        users = await User.findAll({
            where: {
                [Op.or]: [
                    {
                        name: {
                            [Op.like]: `%${keyword}%`
                        }
                    },
                    {
                        age: {
                            [Op.like]: `%${keyword}%`
                        }
                    },
                ]
            }
        })
    } else {
        users = await User.findAll();
    }

    ctx.render("list.html", { users, keyword })
};

//根据id查询单个用户
async function queryById(ctx) {
    let id = ctx.params.id
    console.log("查询单个", id);
    let user = await User.findByPk(id)
    ctx.render('update.html', { user })
};

//根据id删除用户
async function delById(ctx) {
    let id = ctx.params.id;
    console.log("删除用户", id);
    await User.destroy({ where: { id } })
    ctx.body = "删除成功"
};

//新增用户界面
async function addUserView(ctx) {
    ctx.render("add.html", {})
};

//新增用户
async function addUser(ctx) {
    let obj = ctx.request.body;
    console.log("新增用户", obj);

    await User.create(obj);
    ctx.body = '新增成功'
};

//修改用户
async function editUser(ctx) {
    let id = ctx.params.id
    let obj = ctx.request.body;
    console.log("修改用户", obj);
    await User.update(obj, { where: { id } })
    ctx.body = "修改成功"
};

//暴露 定义路由规则
export const users = [
    { method: "GET", path: "/users", fn: queryAll },
    { method: "GET", path: "/user/:id", fn: queryById },
    { method: "GET", path: "/userAdd", fn: addUserView },
    { method: "DELETE", path: "/user/:id", fn: delById },
    { method: "POST", path: "/user", fn: addUser },
    { method: "PUT", path: "/user/:id", fn: editUser }
]